package cn.guet.zjb;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;

import java.net.InetSocketAddress;

public class Client {

  public static void main(String[] args) throws InterruptedException {
    NioEventLoopGroup group = new NioEventLoopGroup();
    try {
      ChannelFuture channelFuture = new Bootstrap()
          .group(group)
          .channel(NioSocketChannel.class)
          .handler(new ChannelInitializer<NioSocketChannel>() {
            @Override
            protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
              nioSocketChannel.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                @Override
                public void channelActive(ChannelHandlerContext ctx) throws Exception {
                  ByteBuf buf = ctx.alloc().buffer();
                  byte[] content = "你好嘻嘻嘻，world".getBytes();
                  buf.writeInt(content.length);
                  buf.writeByte(1);
                  buf.writeBytes(content);
                  ctx.writeAndFlush(buf);

                  ctx.channel().close();
                }
              });
            }
          })
          .connect(new InetSocketAddress("localhost", 8080)).sync();
      channelFuture.channel().closeFuture().sync();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      group.shutdownGracefully();
    }

  }
}
